package com.example.crawler.task;

import com.example.crawler.entity.Chapter;
import com.example.crawler.entity.Content;
import com.example.crawler.entity.Novel;
import com.example.crawler.entity.NovelBO;
import com.example.crawler.service.ChapterService;
import com.example.crawler.service.ContentService;
import com.example.crawler.service.NovelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

/**
 * FileName:  NovelPipeline
 * Author:    REZ_VK
 * Date  :   2019-5-28 0:36
 * info :    这个是..
 */
@Component
public class NovelPipeline implements Pipeline {

    private Logger logger = LoggerFactory.getLogger(NovelPipeline.class);

    @Autowired
    private NovelService novelService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ContentService contentService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //判断数据是否为空
        Novel novel = resultItems.get("novel");
        NovelBO novelBO = resultItems.get("novelBO");
        //小说不为空保存
        if (novel != null) {
            novelService.save(novel);
            logger.info("保存小说《{}》成功",novel.getTitle());
        }
        if(novelBO != null){
            //先查询是那个小说
            List<Novel> tempNovels = novelService.findByTitle(novelBO.getNovel().getTitle());
            if(tempNovels != null){
                //小说不为空,更新第一本
                Novel tempNovel = tempNovels.get(0);
                //更新章节
                Chapter tempChapter = novelBO.getChapter();
                tempChapter.setNId(tempNovel.getId());
                Chapter saveChapter = chapterService.save(tempChapter);
                //更新内容
                Content tempContent = novelBO.getContent();
                tempContent.setCId(saveChapter.getId());
                contentService.save(tempContent);
                logger.info("更新《{}》--{}章节成功",tempNovel.getTitle(),tempChapter.getTitle());
            }else{
                //没有对应的小说
                logger.info("更新章节失败");
            }
        }
    }
}
